const express = require('express');
const uuid = require('node-uuid');
const { Message,MessageList } = require('../utils/message');
const beautyServiceModel = require('../models/beautyService');

const router = express.Router();

router.post('/',(req,res,next)=>{
  const {name,imageUrl,introduction,price,materialName,isConsumeNum} = req.body;
  const id = uuid.v1();
  const beautyService = new beautyServiceModel({id,name,imageUrl,introduction,price,materialName,isConsumeNum});
  beautyService.save().then(data=>{
    if(data){
      res.json(Message(200,'添加成功！'));
    }
  });
});

router.delete('/',(req,res,next)=>{
  const {id}=req.query;
  if(id){
    beautyServiceModel.deleteOne({id}).then(data=>{
      if(data.deletedCount!==0){
        res.json(Message(200,'删除成功！'))
      }else{
        res.json(Message(400,'删除失败'))
      }
    })
  }else{
    res.json(Message(400,'缺少参数id'))
  }
})

router.put('/',(req,res,next)=>{
  const {id}=req.query;
  const {imageUrl,introduction,price,isConsumeNum}=req.body;
  if(id){
    beautyServiceModel.updateOne({id},{imageUrl,introduction,price,isConsumeNum}).then(data=>{
      if(data.acknowledged&&data.modifiedCount!==0){
        res.json(Message(200,'修改成功！'));
      }else{
        res.json(Message(400,'修改失败！'));
      }
    })
  }else{
    res.json(Message(400,'缺少参数id'));
  }
})

router.get('/',(req,res,next)=>{
  const {id,page,pageSize}=req.query;
  const queryObj={};
  if(id) {
    queryObj.id=id
    beautyServiceModel.findOne({id}).then(data=>{
      if(data){
        res.json(Message(200,'',data))
      }else{
        res.json(Message(400,'未查找到相关输！'));
      }
    })
    return
  };
  if(page&&pageSize){
    beautyServiceModel.find(queryObj).count((err,count)=>{
      beautyServiceModel.find(queryObj)
        .limit(pageSize)
        .skip((page-1)*pageSize)
        .then(data=>{
          res.json(MessageList(200,'',data,page,pageSize,count));
        })
    })
  }else{
    beautyServiceModel.find(queryObj).count((err,count)=>{
      beautyServiceModel.find(queryObj).then(data=>{
        if(!id){
          res.json(MessageList(200,'',data,0,0,count));
        }else{
          res.json(Message(200,'',data));
        }
      })
    })
  }
})
module.exports = router